import asap from './asap'
import wrappy from './wrappy'

/**
 * Contain async insanity so that the dark pony lord doesn't eat souls
 * https://github.com/npm/dezalgo
 * @param cb
 * @return {(function(): void)|*}
 */
function dezalgo(cb) {
  let sync = true
  asap(function() {
    sync = false
  })

  return function zalgoSafe() {
    const args = arguments
    const me = this
    if(sync)
      asap(function() {
        cb.apply(me, args)
      })
    else
      cb.apply(me, args)
  }
}

export default wrappy(dezalgo)
